﻿using Common.AspNetCore;
using Common.Infrastructure;
using Log.Api.Extensions;
using Log.Api.Models;
using Log.Api.QueryModel;
using Log.Api.Service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Log.Api.Controllers
{
    [Route("api/DownExtLog")]
    public class DownExtLogController : ApiController
    {
        private DownExtLogService downExtLogContext;

        public DownExtLogController(IServiceProvider provider, DownExtLogService context)
            : base(provider)
        {
            this.downExtLogContext = context;
        }

        /// <summary>
        /// 新增或者修改
        /// </summary>
        /// <param name="downExtLogModel"></param>
        [HttpPost("AddDownExtLog")]
        public async Task<ApiActionResult<bool>> AddDownExtLog([FromBody] DownExtLogModel downExtLogModel)
        {
            return await SafeExecuteAsync<bool>(async (param) =>
            {
                return await downExtLogContext.InsertAsync(downExtLogModel);
            });
        }

        /// <summary>
        /// 删除日志
        /// </summary>
        /// <param name="id"></param>
        [HttpPost("DeleteDownExtLog")]
        public ApiActionResult<bool> DeleteDownExtLog([FromBody] DownExtLogQuery query)
        {
            return SafeExecute<bool>((param) =>
            {
                return downExtLogContext.DeleteByQuery(query);
            });
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost("GetDownExtLogPage")]
        public ApiActionResult<ApiPagedResult<DownExtLogModel>> GetDownExtLogPage([FromBody] DownExtLogQuery query)
        {
            return SafeExecute<ApiPagedResult<DownExtLogModel>>((param) =>
            {
                ApiPagedResult<DownExtLogModel> ret = new ApiPagedResult<DownExtLogModel>();
                if (query.BeginTime == null)
                {
                    query.BeginTime = DateTime.Now.AddDays(-7).Date;
                }

                if (query.EndTime == null)
                {
                    query.EndTime = DateTime.Now.AddDays(1).Date;
                }

                query.BeginTime = ElasticClientExtension.GetDateForEs(query.BeginTime.Value);
                query.EndTime = ElasticClientExtension.GetDateForEs(query.EndTime.Value);
                ret.Data = downExtLogContext.GetDownExtLoges(query);
                var TotalCount = (int)downExtLogContext.GetTotalCount(query);
                ret.TotalCount = TotalCount < 0 ? 0 : TotalCount;
                return ret;
            });
        }
    }
}
